# encoding=utf-8
# MVVM架构中的model，运行环境相关的处理
# BingoLee 2024-05-10
import time
import serial.tools.list_ports as serial_ports

from utils.kit_profile import Profile
from utils.kit_utils import Log, UrlDownloader
from viewmodel.kit_viewmodel import Topic, TopicBinder

from model.kit_data import cache
from model.server_data_parser import server_data_parser


class COMPortHandler:
    """
    串口处理类
    """

    @classmethod
    def update_comport_data(cls):
        while True:
            try:
                comports = sorted([port_info[0] for port_info in serial_ports.comports()])
                if cache.get_comports() != comports:
                    cache.update_comports(comports)
                    TopicBinder.notify(Topic.COMPORTS_DATA_CHANGED, comports)
            except Exception as e:
                Log.error(f'thread excption: update comport data thread: {str(e)}')
            time.sleep(2)


class AppUpgradeHandler:
    """
    App工具升级处理类
    升级策略：自定义AT指令直接替换，配置内容平滑升级
    """

    @classmethod
    def get_version_and_release_note(cls):
        try:
            release_version, err = server_data_parser.get_release_version()
            if release_version is None:
                return None, f"从服务器获取版本Release数据异常:\n{err}"
            release_note = ''
            if int(release_version) > int(Profile.app_version):
                release_note, err = server_data_parser.get_release_note()
                if not release_note:
                    return None, f"从服务器获取版本Release数据异常:\n{err}"
        except Exception as e:
            Log.error(f"thread exception: check release and upgrade thread: {str(e)}")
            return None, f"thread exception: check release and upgrade thread: \n{str(e)}"
        return release_note, None

    @classmethod
    def app_upgrade_handle_callback(cls, data):
        release_version, _ = server_data_parser.get_release_version()

        # Profile.settings_file
        Log.info("TODO upgrade app")


